load mnist_knn;

n = size(IDX,1);

k = 7;
c = 10;
disp('Building graph...');
Ivec = reshape(repmat((1:n)',1,k),[],1);
IDXvec = reshape(IDX(:,2:k+1),[],1);
clear IDX;
Dvec = reshape(DIST(:,2:k+1).^2,[],1);
clear M;
Dvec = Dvec/max(Dvec);

A = sparse(Ivec,IDXvec,Dvec);
A = A + A';
A = (A~=0);
disp('Graph finished!');
save('7nng','A');

disp('Check connectivity...');

%check connected
[S,~] = graphconncomp(A,'Directed',false);
if(S > 1)
    error('Graph not connected! Try more neighbors.');
end
disp('Graph connected!');

B = adj2inc(A);
clear A;

L = double(B)'*double(B);
clear B;
DD = diag(L);
L = 2*sparse(1:n,1:n,DD) - L;
clear DD;


load mnist_train;
clear xL;

Y = yL';

nump = c*(c-1)/2;
sz = zeros(c,1);
idx = cell(10,1);
for i = 1:c
    idx{i}=find(Y==(i-1));
    sz(i)=size(idx{i},1);
end

ix = cell(c,c);
Y = cell(c,c);

for i = 1:c
    for j = i+1:c
        ix{i,j} = [idx{i};idx{j}];
        Y{i,j} = [ones(sz(i),1);-ones(sz(j),1)];
    end
end

disp('Start optimization...');
tic

fai = zeros(n,nump);

ct = 1;
for i = 1:c
    for j = i+1:c
        tic
        cvx_begin sdp
        cvx_solver sedumi
        variable phi(n,1)
        minimize (phi'*L*phi);
        Y{i,j}.*phi(ix{i,j}) >= ones(sz(i)+sz(j),1);
        cvx_end
        fai(:,ct) = phi;
        ct = ct+1;
        toc
    end
end
